package pageProcessor;

import java.io.FileInputStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import main.ServerGlobals;
import protocol.HTTPRequest;
import protocol.HTTPResponse;

public class JSPOld implements PageProcessorInterface {

	@Override
	public HTTPResponse process(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		// Getting the jar URL which contains target class
		URL[] classLoaderUrls;
		try {
			classLoaderUrls = new URL[] { new URL("file://"+
					System.getProperty("user.dir")+"/"+PageProcessorFactory.WEB_FOLDER+"/"+httpRequest.getfHTTPHttpRequestHeaders().getfURI()) };

			// Create a new URLClassLoader 
			URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);

			// Load the target class

			Class<?> beanClass = urlClassLoader.loadClass(JSPOld
					.getClassName(System.getProperty("user.dir")+"/"+PageProcessorFactory.WEB_FOLDER+"/"+httpRequest.getfHTTPHttpRequestHeaders().getfURI()));
			Constructor<?> constructor = beanClass.getConstructor();
			PageProcessorInterface JSP = (PageProcessorInterface) constructor
					.newInstance();
			HTTPResponse ret = JSP.process(httpRequest, serverGlobals);
			urlClassLoader.close();
			return ret;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		throw new RuntimeException("Something wend wrong in JSP CLASS");
	}

	public static String getClassName(String file) {
		try {
			ZipInputStream zip;

			zip = new ZipInputStream(new FileInputStream(file));
			for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip
					.getNextEntry())
				if (entry.getName().endsWith(".class") && !entry.isDirectory()) {
					// This ZipEntry represents a class. Now, what class does it represent?
					StringBuilder className = new StringBuilder();
					for (String part : entry.getName().split("/")) {
						if (className.length() != 0)
							className.append(".");
						className.append(part);
						if (part.endsWith(".class"))
							className.setLength(className.length()
									- ".class".length());
					}
					zip.close();
					return className.toString();
				}
			zip.close();
		} catch (Exception e) {
			
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
